package com.ev.custom.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.ev.custom.dao.UpkeepRecordDeviceDao;
import com.ev.custom.dao.UpkeepRecordProjectDao;
import com.ev.custom.domain.*;
import com.ev.custom.service.*;
import com.ev.framework.config.ConstantForDevice;
import com.ev.framework.exception.BDException;
import com.ev.framework.utils.StringUtils;
import com.google.common.collect.Maps;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;


@EnableTransactionManagement
@Service
public class UpkeepRecordDeviceServiceImpl implements UpkeepRecordDeviceService {
	@Autowired
	private UpkeepRecordDeviceDao upkeepRecordDeviceDao;
	@Autowired
	private ContentAssocService contentAssocService;
	@Autowired
	private DeviceService deviceService;
	@Autowired
	private UpkeepRecordProjectDao upkeepRecordProjectDao;
	@Autowired
	private UpkeepRecordService upkeepRecordService;
	private MaterielService materielService;

	@Override
	public UpkeepRecordDeviceDO get(Integer id){
		return upkeepRecordDeviceDao.get(id);
	}

	@Override
	public List<UpkeepRecordDeviceDO> list(Map<String, Object> map){
		return upkeepRecordDeviceDao.list(map);
	}

	@Override
	public int count(Map<String, Object> map){
		return upkeepRecordDeviceDao.count(map);
	}

	@Override
	public int save(UpkeepRecordDeviceDO upkeepRecordDevice){
		return upkeepRecordDeviceDao.save(upkeepRecordDevice);
	}

	@Override
	public int update(UpkeepRecordDeviceDO upkeepRecordDevice){
		return upkeepRecordDeviceDao.update(upkeepRecordDevice);
	}

	@Override
	public int remove(Integer id){
		return upkeepRecordDeviceDao.remove(id);
	}

	@Override
	public int batchRemove(Integer[] ids){
		return upkeepRecordDeviceDao.batchRemove(ids);
	}

	@Override
	public List<Map<String, Object>> deviceByRecordId(Map<String, Object> map) {
		List<Map<String, Object>> deviceListMap = upkeepRecordDeviceDao.deviceByRecordId(map);
		if(CollectionUtil.isNotEmpty(deviceListMap)){
			for (Map<String, Object> deviceMap : deviceListMap) {
				// 点检图片
				Map<String, Object> deviceImgParam = Maps.newHashMapWithExpectedSize(2);
				deviceImgParam.put("assocId",deviceMap.get("id"));
				deviceImgParam.put("assocType", ConstantForDevice.UNKEEP_RECORD_DEVICE_IMAGE);
				List<ContentAssocDO> deviceImgContentAssocDO = contentAssocService.list(deviceImgParam);
				deviceMap.put("fileList", deviceImgContentAssocDO);
			}
		}
		return deviceListMap;
	}

	@Override
	public List<Map<String, Object>> deviceByRecordIdAgain(Map<String, Object> map) {
		return upkeepRecordDeviceDao.deviceByRecordIdAgain(map);
	}

	@Override
	public void updateRecordDeviceDetail(String project, String parts, UpkeepRecordDO upkeepRecordDO, List<String> taglocationappearanceImage,String devices) {

		Long recordId=upkeepRecordDO.getId();

		Long planId=upkeepRecordService.get(recordId)!=null?upkeepRecordService.get(recordId).getPlanId():null;

		//保存工单下保养项目
		this.doSaveAndChangePro(project,recordId,planId);
		//保存图片
		contentAssocService.saveList(recordId, taglocationappearanceImage, ConstantForDevice.UNKEEP_RECORD_IMAGE);
		JSONObject jsonObject;
		if(StringUtils.isEmpty(devices)){
			jsonObject = null;
		}else{
			jsonObject = JSONObject.fromObject(devices);
		}
		JSONArray jsonArray;
		if(jsonObject == null){
			jsonArray= new JSONArray();
		}else{
			jsonArray = JSONArray.fromObject(jsonObject.get("dataList"));
		}

		//将所有工单下设备全部删除+保存
		upkeepRecordDeviceDao.removeByRecordId(recordId);
		for (int i = 0; i < jsonArray.size(); i++) {
			Map<String, Object> mapsDetail = (Map<String, Object>) jsonArray.get(i);
			UpkeepRecordDeviceDO upkeepRecordDeviceDO = new UpkeepRecordDeviceDO();
			upkeepRecordDeviceDO.setPlanId(planId);
			upkeepRecordDeviceDO.setRecordId(recordId);
			upkeepRecordDeviceDO.setDeviceId(Long.parseLong(mapsDetail.containsKey("deviceId")?mapsDetail.get("deviceId").toString():null));
			upkeepRecordDeviceDO.setDeviceName(mapsDetail.containsKey("deviceName")?mapsDetail.get("deviceName").toString():null);
			upkeepRecordDeviceDO.setDeviceCode(mapsDetail.containsKey("deviceCode")?mapsDetail.get("deviceCode").toString():null);
			upkeepRecordDeviceDO.setModel(mapsDetail.containsKey("model")?mapsDetail.get("model").toString():null);
			upkeepRecordDeviceDO.setCompleteTime(mapsDetail.containsKey("completeTime")? DateUtil.parse(mapsDetail.get("completeTime").toString(),"yyyy-MM-dd HH:mm:ss") :null);
			upkeepRecordDeviceDO.setRemark(mapsDetail.containsKey("remark")?mapsDetail.get("remark").toString():"");
			DeviceDO deviceDO = deviceService.get(upkeepRecordDeviceDO.getDeviceId());

			if(deviceDO==null){
				throw new BDException(upkeepRecordDeviceDO.getDeviceName()+"该设备不存在！");
			}
			upkeepRecordDeviceDO.setModel(deviceDO.getModel());
			upkeepRecordDeviceDO.setDeviceCode(deviceDO.getSerialno());

			upkeepRecordDeviceDao.save(upkeepRecordDeviceDO);

			//保存图片

			String fileListStr = mapsDetail.get("fileList").toString();

			if (fileListStr != null && StrUtil.isNotEmpty(fileListStr)) {
				List<ContentAssocDO> deviceImage = JSON.parseArray(fileListStr,ContentAssocDO.class);
				for (ContentAssocDO contentAssocDO : deviceImage) {
					contentAssocDO.setAssocId(upkeepRecordDeviceDO.getId());
					contentAssocDO.setAssocType(ConstantForDevice.UNKEEP_RECORD_DEVICE_IMAGE);
					contentAssocService.save(contentAssocDO);
				}
			}
		}
		upkeepRecordService.update(upkeepRecordDO);
	}

	@Override
	public int removeByRecordId(Long id) {
		return upkeepRecordDeviceDao.removeByRecordId(id);
	}

	@Override
	public int batchRemoveByRecordId(Long[] ids) {
		return upkeepRecordDeviceDao.batchRemoveByRecordId(ids);
	}


	/**
	 * 更新保存工单下保养项目
	 * @param project
	 */
	public void doSaveAndChangePro(String project,Long recoldId,Long planId){
		//{"dataList":[{"projectId":3,"manhour":5,"result":1(1正常，0异常),"remark":"备注"},{"projectId":3,"manhour":5,"result":1,"remark":"备注"}]}
		//{"dataList":[{"projectId":3,"manhour":5,"manHourCost":100,"result":1(1正常，0异常),"remark":"备注"},{"projectId":3,"manhour":5,"manHourCost":100,"result":1(1正常，0异常),"remark":"备注"}]}
		//先删除所有保项目
		upkeepRecordProjectDao.removeByRecordId(recoldId);

		JSONObject jsonObject = JSONObject.fromObject(project);
		JSONArray jsonArray = JSONArray.fromObject(jsonObject.get("dataList"));
		for (int i = 0; i < jsonArray.size(); i++) {
			Map<String, Object> mapsDetail = (Map<String, Object>) jsonArray.get(i);
			UpkeepRecordProjectDO uRPDo = new UpkeepRecordProjectDO();
			uRPDo.setPlanId(planId);
			uRPDo.setRecordId(recoldId);
			uRPDo.setProjectId(Long.parseLong(mapsDetail.containsKey("projectId")?mapsDetail.get("projectId").toString():null));
//			uRPDo.setManhour(Integer.parseInt(mapsDetail.containsKey("manhour")?mapsDetail.get("manhour").toString():null));
			uRPDo.setManhour((mapsDetail.containsKey("manhour") && !ObjectUtils.isEmpty(mapsDetail.get("manhour"))) ? new Integer(mapsDetail.get("manhour").toString()) : null);
			uRPDo.setResult((mapsDetail.containsKey("result") && !ObjectUtils.isEmpty(mapsDetail.get("result"))) ? new Integer(mapsDetail.get("result").toString()) : null);
//			uRPDo.setResult(Integer.parseInt(mapsDetail.containsKey("result")?mapsDetail.get("result").toString():null));
			uRPDo.setRemark((mapsDetail.containsKey("remark") && !ObjectUtils.isEmpty(mapsDetail.get("remark"))) ? mapsDetail.get("remark").toString() : "");
//			uRPDo.setRemark(mapsDetail.containsKey("remark")?mapsDetail.get("remark").toString():"");
			uRPDo.setManHourCost((mapsDetail.containsKey("manHourCost") && !ObjectUtils.isEmpty(mapsDetail.get("manHourCost"))) ? new BigDecimal(mapsDetail.get("manHourCost").toString()) : new BigDecimal(0));
//			uRPDo.setManHourCost(mapsDetail.containsKey("manHourCost")?new BigDecimal(Double.parseDouble(mapsDetail.get("manHourCost").toString())):new BigDecimal(0));
			upkeepRecordProjectDao.save(uRPDo);
		}


	}



}
